<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\Request;
use \StudyBuddy\Responder;
use \StudyBuddy\AnswerParser;
use \StudyBuddy\SubmittedAnswerWWW;

/**
 * Controller for processing the answer form
 * It extends wwwViewquestion because in case of form validation
 * we will be able to just return the page with question plus
 * the same form with errors added to it.
 *
 */
class Answer extends Viewquestion
{

	protected $permission = 'answer';

	protected $membersOnly = true;

	//protected $aAllowedVars = array('qbody');


	protected function main(){
		$this->getQuestion()->makeForm();
		if($this->oForm->validate()){
			/**
			 * The process() will either send out
			 * json for ajax request OR will
			 * redirect to page, in either case
			 * we will not get to makeHtml() method
			 *
			 */
			$this->process();
		} else {
			/**
			 * Need to show entire question page with
			 * form appended (it will contain errors this time)
			 */
			$this->showFormWithErrors();
		}
	}


	protected function showFormWithErrors(){
		$this->setTitle()
		->setAnswersHeader()
		->setAnswers()
		->setSimilar()
		->setAnswerForm()
		->setFooter();
	}


	/**
	 * Process submitted Answer
	 * 
	 * @return void
	 */
	protected function process(){
		$formVals = $this->oForm->getSubmittedValues();
		d('formVals: '.print_r($formVals, 1));
		$oAdapter = new AnswerParser($this->oRegistry);
		try{
			$oAnswer = $oAdapter->parse(new SubmittedAnswerWWW($this->oRegistry, $formVals));
			d('cp created new answer: '.print_r($oAnswer->getArrayCopy(), 1));
			d('ans id: '.$oAnswer->getResourceId());

			/**
			 * In case of ajax we need to send out a
			 * parsed html block with one answer
			 * under the 'answer' key
			 *
			 * In case of non-ajax redirect back to question page,
			 * hopefull the new answer will show up there too
			 */
			if(Request::isAjax()){
				$aAnswer = $oAnswer->getArrayCopy();
				/**
				 * Add edit and delete tools because
				 * Viewer already owns this comment and is
				 * allowed to edit or delete it right away.
				 * Javascript that usually dynamically adds these tools
				 * is not going to be fired, so these tools
				 * must alreayd be included in the returned html
				 *
				 */
				$aAnswer['edit_delete'] = ' <span class="ico del ajax" title="Delete">delete</span>  <span class="ico edit ajax" title="Edit">edit</span>';
				$a = array('answer' => \tplAnswer::parse($aAnswer));
				d('before sending out $a: '.print_r($a, 1));

				Responder::sendJSON($a);

			} else {
				Responder::redirectToPage($this->oQuestion->getUrl());
			}

		} catch (\StudyBuddy\AnswerParserException $e){
			/**
			 * The setFormError in Form sends our json in
			 * case of Ajax request, so we don't have to
			 * worry about it here
			 */
			$this->oForm->setFormError($e->getMessage());
			$this->showFormWithErrors();
		}
	}
}
